package com.zhouqinuan.spring.cloud.develop.framework.web;

import javax.servlet.http.HttpServletRequest;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import com.alibaba.fastjson.JSON;

@ControllerAdvice
public class ControllerResponseBodyAdvice implements ResponseBodyAdvice {

	private static final String RESP_BODY_ATTRIBUTE = "RESP_BODY_ATTRIBUTE";

	@Override
	public boolean supports(MethodParameter returnType, Class converterType) {
		return true;
	}

	@Override
	public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
			Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

		HttpServletRequest httpServletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		String bodyAttribute = "";

		if (body instanceof String) {
			bodyAttribute = (String) body;

		} else {
			bodyAttribute = JSON.toJSONString(body);
		}

		httpServletRequest.setAttribute(RESP_BODY_ATTRIBUTE, bodyAttribute);

		return body;
	}

}
